unit GameUnit;

interface

uses PlayerUnit, Types, ExtCtrls, SortUnit, common, Graphics, ballUnit, SysUtils;

const X0 = 0;
      Y0 = 0;
      WIDTH = 200;

type
  Game = class
    score : integer;
    kingKong : integer;
    w : double;
    p : Player;
    im : TImage;
    s : Sort;
    b : Ball;
    state, _last : integer;
    arr : array of integer;
    constructor Create(_p : Player; _im : TImage; _arr : array of integer);
    procedure Draw;
    procedure DrawArray;

    procedure Step;
  end;

implementation

{ Game }

constructor Game.Create;
var i : integer;
begin
  p := _p;
  im := _im;
  setLength(arr, N);
  for i := 0 to N-1 do
    arr[i] := _arr[i];

  s := Sort.Create;

  state := 0;
  score := 0;
end;

procedure Game.Draw;

begin
  im.Canvas.Brush.Color := clWhite;
  im.Canvas.Rectangle(im.ClientRect);
  drawArray;
end;

procedure Game.DrawArray;
var i : integer;
    BSource:Tbitmap;
    Rect1, Rect2:Trect;
begin
  w := im.WIDTH / N;
  for i := 0 to N-1 do
  begin
    im.Canvas.Brush.Color := clWhite;
    if (i >= N-s.runNumber) then
      im.Canvas.Brush.Color := clBlue;
    if (s.number = i) or (s.number+1 = i)then
      im.Canvas.Brush.Color := clRed;
    im.Canvas.Rectangle(round(X0+i*w), y0+_HEIGHT-arr[i], round(X0+(i+1)*w), y0+_HEIGHT);
  end;
   im.Canvas.Brush.Color := clWhite;
  im.Canvas.TextOut(5,5,IntToStr(score));

  BSource:=TBitMap.Create;
  BSource.LoadFromFile('king2.bmp');
  Rect1:=Bounds(round(X0+s.number*w),_HEIGHT,100,100);
  Rect2:=Bounds(0,0,100,100);
  im.Canvas.CopyRect(Rect1,BSource.Canvas,Rect2);
  BSource.Free;
  BSource:=TBitMap.Create;  
  BSource.LoadFromFile('godzilla.bmp');
  Rect1:=Bounds(round(X0+_last*w),im.Height-55,100,100);
  Rect2:=Bounds(0,0,100,100);
  im.Canvas.CopyRect(Rect1,BSource.Canvas,Rect2);
  BSource.Free;
end;

procedure Game.Step;
var res, h : integer;
begin
  if state = 0 then
  begin
    h := 2+random(_HEIGHT);
    res := p.move(h, s.number, s.runNumber, arr);
    _last := res;
    if (res >= 0) then
    begin
      state := 1;
      b := Ball.Create(round(X0+res*w+w/2), 200, h);
    end;
  end else if (state = 1) then
  begin
    b.move;
    if (b.y <= _HEIGHT) then
    begin
      if (arr[_last] <= b.h) then
      begin
        inc(score);
      end else begin
        if (_last < N-s.runNumber) then begin
          arr[_last] := b.h;
          if (_last = s.number+1) then
            s.number := 0;
        end;
      end;
      state := 0;
    end;
    Draw;
    b.Draw(im);
  end;
  if (state < 2) then
  begin
    inc(kingKong);
    if (kingKong = 3) then
    begin
      kingKong := 0;
      if s.step(arr) = false then
        state := 3;
    end;
  end;
end;

end.
